package team.xstudio.bedwarstoolkit.ingame

import net.minecraft.world.entity.player.Player
import net.minecraftforge.event.TickEvent
import team.xstudio.bedwarstoolkit.utils.BWUtils.getSkyLevel
import kotlin.jvm.optionals.getOrNull

/**
 * Created in 2025/6/10
 * Project: bedwarstoolkit
 *
 * @author <a href="https://github.com/Bread-Nicecat">Bread_NiceCat</a>
 * <p>
 *
 * <p>
 **/
object BWGameManager {
    private var counter = 0;
    private val games = LinkedHashSet<BWGameInstance>()

    fun getGames(): Iterable<BWGameInstance> = games
    fun isInGame(player: Player): Boolean = getGameByPlayer(player) != null

    fun getGameByPlayer(player: Player): BWGameInstance? =
        games.stream().filter { it.hasPlayer(player) }.findFirst().getOrNull()

    fun getTeamByPlayer(player: Player): BWGameTeam? = getGameByPlayer(player)?.getTeamByPlayer(player)

    fun newGame() {
    }

    //===========================
    // Event Handlers
    //===========================
    fun onServerTick(event: TickEvent.ServerTickEvent) {
        if (event.phase == TickEvent.Phase.START) {
            val server = event.server
            games.forEach {
                it.serverTick(server.getSkyLevel())
            }
        }
    }

}